﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using Newtonsoft.Json;

namespace ERP_SaaS_WinForm.采购管理
{
    public partial class Inspection : CCSkinMain
    {
        private Quality _qualityForm; // 保存Quality窗体的引用
        
        public Inspection(Quality qualityForm = null)
        {
            InitializeComponent();
            
            // 保存Quality窗体的引用
            _qualityForm = qualityForm;
            
            // 设置窗体标题
            this.Text = "质检人员选择";
            
            // 加载质检人员数据
            this.Load += Inspection_Load;
            
            // 绑定双击事件
            skinDataGridView1.CellDoubleClick += SkinDataGridView1_CellDoubleClick;
            
            // 绑定确认按钮点击事件
            QQur.Click += QQur_Click;
        }
        
        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private async void Inspection_Load(object sender, EventArgs e)
        {
            await LoadInspectors();
        }
        
        /// <summary>
        /// 加载质检人员数据
        /// </summary>
        private async Task LoadInspectors()
        {
            try
            {
                // 显示加载状态
                skinDataGridView1.Rows.Clear();
                skinDataGridView1.Rows.Add("正在加载...", "");
                
                // 使用正确的质检人员API接口
                string apiUrl = "http://10.223.8.2:4090/api/Supplier/GetUserInfo";
                
                using (HttpClient client = new HttpClient())
                {
                    var response = await client.GetAsync(apiUrl);
                    response.EnsureSuccessStatusCode();
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    
                    var apiResponse = JsonConvert.DeserializeObject<InspectorApiResponse>(jsonResponse);
                    
                    if (apiResponse.code == 200 && apiResponse.datas != null && apiResponse.datas.Count > 0)
                    {
                        // 清空现有数据
                        skinDataGridView1.Rows.Clear();
                        
                        // 添加质检人员数据，使用PlanDatas.cs中定义的字段
                        foreach (var inspector in apiResponse.datas)
                        {
                            int rowIndex = skinDataGridView1.Rows.Add();
                            skinDataGridView1.Rows[rowIndex].Cells["Column1"].Value = inspector.qiId.ToString();
                            skinDataGridView1.Rows[rowIndex].Cells["Column2"].Value = inspector.qiName;
                            
                            // 保存质检人员信息到行标签中
                            skinDataGridView1.Rows[rowIndex].Tag = inspector;
                        }
                        
                        Console.WriteLine($"成功加载 {apiResponse.datas.Count} 个质检人员");
                    }
                    else
                    {
                        // 如果API没有数据，添加一些测试数据
                        AddTestData();
                    }
                }
            }
            catch (Exception ex)
            {
                skinDataGridView1.Rows.Clear();
                skinDataGridView1.Rows.Add("加载失败", ex.Message);
                Console.WriteLine($"加载质检人员数据失败：{ex.Message}");
            }
        }
        
        /// <summary>
        /// 添加测试数据
        /// </summary>
        private void AddTestData()
        {
            skinDataGridView1.Rows.Clear();
            
            // 添加一些测试数据
            skinDataGridView1.Rows.Add("001", "张三");
            skinDataGridView1.Rows.Add("002", "李四");
            skinDataGridView1.Rows.Add("003", "王五");
            skinDataGridView1.Rows.Add("004", "赵六");
            
            Console.WriteLine("已添加测试数据");
        }
        
        /// <summary>
        /// 双击选择质检人员
        /// </summary>
        private void SkinDataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.RowIndex < skinDataGridView1.Rows.Count)
            {
                var selectedRow = skinDataGridView1.Rows[e.RowIndex];
                var userInfo = selectedRow.Tag as InspectorData;
                
                if (userInfo != null)
                {
                    // 显示选中的质检人员信息
                    string message = $"已选择质检人员：\n编号：{userInfo.qiId.ToString()}\n姓名：{userInfo.qiName}";
                    MessageBox.Show(message, "选择成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    Console.WriteLine($"已选择质检人员: {userInfo.qiName} (ID: {userInfo.qiId})");
                    
                    // 可以在这里添加其他处理逻辑，比如关闭窗体或返回选择结果
                }
                else
                {
                    // 如果没有用户信息，显示行数据
                    string userCode = selectedRow.Cells["Column1"].Value?.ToString() ?? "";
                    string userName = selectedRow.Cells["Column2"].Value?.ToString() ?? "";
                    
                    if (!string.IsNullOrEmpty(userName))
                    {
                        string message = $"已选择质检人员：\n编号：{userCode}\n姓名：{userName}";
                        MessageBox.Show(message, "选择成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        
                        Console.WriteLine($"已选择质检人员: {userName} (编号: {userCode})");
                    }
                }
            }
        }
        
        /// <summary>
        /// 确认按钮点击事件 - 将选中的质检人员信息返回给Quality窗体
        /// </summary>
        private void QQur_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取当前选中的行
                if (skinDataGridView1.SelectedRows.Count > 0)
                {
                    var selectedRow = skinDataGridView1.SelectedRows[0];
                    var inspectorData = selectedRow.Tag as InspectorData;
                    
                    if (inspectorData != null)
                    {
                        // 如果有Quality窗体引用，将数据返回
                        if (_qualityForm != null)
                        {
                            // 尝试多种方式设置QualityInspector文本框的值
                            bool success = false;
                            
                            // 方法1：使用反射访问私有字段
                            var qualityInspectorField = _qualityForm.GetType().GetField("QualityInspector", 
                                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                            
                            if (qualityInspectorField != null)
                            {
                                var textBox = qualityInspectorField.GetValue(_qualityForm);
                                if (textBox != null)
                                {
                                    // 尝试设置Text属性
                                    var textProperty = textBox.GetType().GetProperty("Text");
                                    if (textProperty != null)
                                    {
                                        textProperty.SetValue(textBox, inspectorData.qiName);
                                        success = true;
                                    }
                                }
                            }
                            
                            // 方法2：如果方法1失败，尝试使用公共属性
                            if (!success)
                            {
                                var qualityInspectorProperty = _qualityForm.GetType().GetProperty("QualityInspector");
                                if (qualityInspectorProperty != null)
                                {
                                    var textBox = qualityInspectorProperty.GetValue(_qualityForm);
                                    if (textBox != null)
                                    {
                                        var textProperty = textBox.GetType().GetProperty("Text");
                                        if (textProperty != null)
                                        {
                                            textProperty.SetValue(textBox, inspectorData.qiName);
                                            success = true;
                                        }
                                    }
                                }
                            }
                            
                            if (success)
                            {
                                // 显示成功消息
                                MessageBox.Show($"已选择质检人员：{inspectorData.qiName}\n数据已返回给Quality页面", 
                                    "选择成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                
                                Console.WriteLine($"已返回质检人员信息: {inspectorData.qiName} (ID: {inspectorData.qiId})");
                                
                                // 关闭当前窗体
                                this.Close();
                            }
                            else
                            {
                                MessageBox.Show($"选择成功：{inspectorData.qiName}\n但数据返回失败，请手动填写", 
                                    "部分成功", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                this.Close();
                            }
                        }
                        else
                        {
                            // 如果没有Quality窗体引用，只显示选择信息
                            string message = $"已选择质检人员：\n编号：{inspectorData.qiId}\n姓名：{inspectorData.qiName}";
                            MessageBox.Show(message, "选择成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        // 如果没有质检人员数据，显示行数据
                        string userCode = selectedRow.Cells["Column1"].Value?.ToString() ?? "";
                        string userName = selectedRow.Cells["Column2"].Value?.ToString() ?? "";
                        
                        if (!string.IsNullOrEmpty(userName))
                        {
                            if (_qualityForm != null)
                            {
                                // 尝试设置QualityInspector文本框的值
                                bool success = false;
                                
                                var qualityInspectorField = _qualityForm.GetType().GetField("QualityInspector", 
                                    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                                
                                if (qualityInspectorField != null)
                                {
                                    var textBox = qualityInspectorField.GetValue(_qualityForm);
                                    if (textBox != null)
                                    {
                                        var textProperty = textBox.GetType().GetProperty("Text");
                                        if (textProperty != null)
                                        {
                                            textProperty.SetValue(textBox, userName);
                                            success = true;
                                        }
                                    }
                                }
                                
                                if (success)
                                {
                                    MessageBox.Show($"已选择质检人员：{userName}\n数据已返回给Quality页面", 
                                        "选择成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    this.Close();
                                }
                                else
                                {
                                    MessageBox.Show($"选择成功：{userName}\n但数据返回失败，请手动填写", 
                                        "部分成功", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    this.Close();
                                }
                            }
                            else
                            {
                                string message = $"已选择质检人员：\n编号：{userCode}\n姓名：{userName}";
                                MessageBox.Show(message, "选择成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                        else
                        {
                            MessageBox.Show("请先选择一个质检人员！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("请先选择一个质检人员！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"确认选择时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"异常详情: {ex}");
            }
        }
    }
    
    /// <summary>
    /// 质检人员API响应结果
    /// </summary>
    public class InspectorApiResponse
    {
        public string msg { get; set; }
        public int code { get; set; }
        public List<InspectorData> datas { get; set; }
    }

    /// <summary>
    /// 质检人员信息模型（来自API，对应PlanDatas.cs中的字段）
    /// </summary>
    public class InspectorData
    {
        /// <summary>
        /// 质检人员ID，对应PlanDatas.cs中的qIId
        /// </summary>
        public int qiId { get; set; }
        
        /// <summary>
        /// 质检人员姓名，对应PlanDatas.cs中的qIName
        /// </summary>
        public string qiName { get; set; }
        
        /// <summary>
        /// 是否已删除
        /// </summary>
        public bool isDeleted { get; set; }
    }
}
